package com.minsf.starter.bootstrap;

/**
 * @Description
 * @Author minify
 * @Date 2024/4/1 22:00
 * @Project sf-rpc
 */

import com.minsf.rpc.RpcApplication;
import com.minsf.rpc.config.RegistryConfig;
import com.minsf.rpc.config.RpcConfig;
import com.minsf.rpc.model.ServiceMetaInfo;
import com.minsf.rpc.model.ServiceRegisterInfo;
import com.minsf.rpc.registry.LocalRegistry;
import com.minsf.rpc.registry.Registry;
import com.minsf.rpc.registry.RegistryFactory;
import com.minsf.rpc.server.tcp.VertxTcpServer;
import com.minsf.starter.annotion.RpcService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.List;

/**
 * 服务提供者启动
 */
public class RpcProviderBootstrap implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        RpcService rpcService = beanClass.getAnnotation(RpcService.class);

        if(rpcService != null) {
            // 需要注册服务
            // 1.获取服务基本信息
            Class<?> interfaceClass = rpcService.interfaceClass();
            // 默认值处理
            if (interfaceClass == void.class) {
                interfaceClass = beanClass.getInterfaces()[0];
            }

            String serviceName = interfaceClass.getName();
            String serviceVersion = rpcService.serviceVersion();
            // 2.注册服务
            // 本地注册
            LocalRegistry.registry(serviceName, beanClass);

            // 全局配置
            RpcConfig rpcConfig = RpcApplication.getRpcConfig();
            // 注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());

            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceVersion(serviceVersion);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());

            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + "服务注册失败", e);
            }
        }

        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);

    }
}
